/*
 * hooks工具库
 * @Author: linzy
 * @Date: 2022-06-17
 */
import moment from "moment";
import _ from "lodash";
import BraftEditor from "braft-editor";
import xlsx from "xlsx";
import appState from "@/models/app";
import * as gConfig from "@/config";
const mpJumpObj = _.keyBy(gConfig.mpJumpOptions, "value");
const mpJumpEnum = {
  H5: 10
};
/**
 * 获取完整的时间戳 兼容返回秒而不是毫秒的时间戳
 * @param {number} stamp
 * @returns
 */
export function getFullStamp(stamp) {
  return String(stamp).length < 11 ? stamp * 1000 : stamp;
}

/**
 * 日期 格式化
 *
 * @param {number} stamp - 时间戳
 * @param {string} mode - 模式
 * @returns {string} - 格式化后的日期
 */
export function getDateFormat(stamp, mode = "dateTime") {
  if (!stamp) return "";
  stamp = getFullStamp(stamp);
  let format;
  switch (mode) {
    case "year":
      format = "YYYY";
      break;
    case "month":
      format = "YYYY-MM";
      break;
    case "date":
      format = "YYYY-MM-DD";
      break;
    case "dateMinute":
      format = "YYYY-MM-DD HH:mm";
      break;
    case "dateTime":
    case "datetime":
      format = "YYYY-MM-DD HH:mm:ss";
      break;
    default:
      break;
  }
  return moment(stamp).format(format);
}
/**
 * 秒转化成剩余时间
 *
 * @param {number} num - 秒数
 */
export function getTimeBySeconds(num) {
  const dayUnit = 24 * 60 * 60;
  const hourUnit = 60 * 60;
  const minuteUnit = 60;
  const days = ~~(num / dayUnit);
  const hours = ~~((num %= dayUnit) / hourUnit);
  const minutes = ~~((num %= hourUnit) / minuteUnit);
  const seconds = (num %= minuteUnit);
  return (
    (days ? days + "天" : "") +
    (hours ? hours + "时" : "") +
    (minutes ? minutes + "分" : "") +
    (seconds ? seconds + "秒" : "")
  );
}
/**
 * 设置外部属性，用于在封装的时候使用
 *
 * @param {object} props 响应的props
 * @param {object} attrs 外部属性的对象
 */
export function setOutAttrs(props, attrs) {
  for (const [key, val] of Object.entries(attrs)) {
    val !== undefined && (props[key] = props[key] ?? val);
  }
}
/**
 * 设置默认属性
 *
 * @param {object} props
 * @param {*} attrs key:value 属性名
 */
export function setDefaultAttrs(props, attrs) {
  for (const [key, val] of Object.entries(attrs)) {
    props[key] === undefined && (props[key] = val);
  }
}
/**
 * 复写属性
 *
 * @param {object} props
 * @param {*} attrs key:value 属性名
 */
export function setOverwriteAttrs(props, attrs) {
  for (const [key, val] of Object.entries(attrs)) {
    props[key] = function () {
      val();
      props[key] && props[key]();
    };
  }
}
/**
 * 设置对象的别名 使用起来更加方便
 *
 * @param {*} props
 * @param {*} attrs  key:value key => 原来的属性名 value => 别名
 */
export function setAlias(props, attrs) {
  for (const [key, val] of Object.entries(attrs)) {
    props[val] !== undefined && (props[key] = props[key] ?? props[val]);
  }
}
/**
 * 获取col组件的自适应参数
 *
 * @param {number} times 倍数 range组件传入2
 * @returns
 */
export function getColProps(times = 1) {
  return {
    xs: 24,
    sm: 12 * times,
    md: 8 * times,
    lg: 6 * times,
    xl: 6 * times,
    xxl: 4 * times
  };
}
/**
 * @description 转化中文数字 现仅支持万内数字转化
 * @function chinese2num
 * @param {string} chineseNum
 * @param {number} name=123  名称
 * @param {*} age - 年龄
 * @property {function} cb - 回调函数
 * @returns {number|boolean}
 */
export const chinese2num = (chineseNum, name = 123, age, cb) => {
  const reg = /(一|二|两|三|四|五|六|七|八|九|十|百|千|万)+/;
  if (!reg.test(chineseNum)) return null;
  const numObj = {
    一: 1,
    二: 2,
    两: 2,
    三: 3,
    四: 4,
    五: 5,
    六: 6,
    七: 7,
    八: 8,
    九: 9
  };
  const unitObj = {
    十: 10,
    百: 100,
    千: 1000,
    万: 10000
  };
  function isUnit(w) {
    return !!unitObj[w];
  }
  var str = reg.exec(chineseNum)[0];
  var sum = 0;
  for (let i = 0; i < str.length; i++) {
    if (isUnit(str[i])) {
      sum += unitObj[str[i]];
    } else if (str[i + 1] && isUnit(str[i + 1])) {
      sum += unitObj[str[i + 1]] * numObj[str[i]];
      i++;
    } else {
      sum += numObj[str[i]];
    }
  }
  return sum;
};
/**
 * 返回短信条数
 *
 * @param {*} value 短信内容
 * @param {*} headCount 短信额外内容的长度 默认12
 * @returns
 */
export function getShortMessageCount(value, headCount = 12) {
  if (!value) return 0;
  if (value.length <= 70 - headCount) {
    return 1;
  } else {
    return Math.ceil((value.length + headCount) / 67);
  }
}
/**
 * 计算表格的width
 * @param {number} count 表格内容的字数
 * @param {boolean} isBorder 表格是否有border属性
 * @returns {string}
 * 使用场景：
 *  在表格传递columns 限制表格的宽度 比如限制状态只有四个字的 传 width: getTdWidth(4)
 */
export const getTdWidth = (count, isBorder = false) => {
  if (count) {
    return `${count * 14 + 32 + (isBorder ? 2 : 0)}px`;
  } else {
    return "fit-content";
  }
};
/**
 * 获取类型
 *
 * @param {*} any
 * return {string}
 */
export function typeOf(any) {
  const str = Object.prototype.toString.call(any);
  return str.slice(8, -1).toLowerCase();
}
/**
 * 转换form表单submit成功后的values对象 主要是改日期转换成时间戳
 * 把values中的undefined改为null 再通过接口传递给后台
 *
 * @param {object} values 表单submit生成的values对象
 * @param {array} formItems 表单的formItems
 * @returns {object} newValues
 */
export function transformValues(values = {}, formItems = []) {
  const newValues = _.cloneDeep(values);
  formItems
    .filter(item => item.exclude !== true && item.name)
    .forEach((formItem, index, list) => {
      const { name, type, encode } = formItem;
      const value = getValue(values, name);
      // 处理小程序跳转
      if (formItem.mode === "mpJump") {
        let mpJumpItem = getMpJumpItem({
          formItems: list,
          index,
          detail: values
        });
        if (mpJumpItem) {
          let newVal =
            mpJumpItem.value === mpJumpEnum.H5
              ? getEncodeUrl(mpJumpItem.prefix + String(value).trim(), "?url=")
              : mpJumpItem.prefix + String(value).trim();
          setValue(newValues, name, newVal);
          return;
        }
      }
      setValue(newValues, name, value);
      if (value === undefined) {
        if (/\,/.test(name)) {
          name.split(",").forEach(item => setValue(newValues, item, null));
        } else {
          setValue(newValues, name, null);
        }
      }
      if (value === "") {
        setValue(newValues, name, null);
      }
      if (!value) return;
      if (/Date/i.test(type)) {
        setValue(newValues, name, value.valueOf());
        if (formItem.startOf) {
          setValue(newValues, name, value.startOf("day").valueOf());
        } else if (formItem.endOf) {
          setValue(newValues, name, value.endOf("day").valueOf());
        } else {
          setValue(newValues, name, value.valueOf());
        }
      } else if (/^(Month|Week|Year)$/i.test(formItem.type)) {
        const nameList = name.split(",");
        nameList.forEach((item, index) => {
          if (index === 0) {
            setValue(
              newValues,
              item,
              formItem.endOf
                ? moment(value).endOf(type.toLowerCase()).valueOf()
                : moment(value).startOf(type.toLowerCase()).valueOf()
            );
          } else {
            setValue(
              newValues,
              item,
              value
                ? moment(value).endOf(type.toLowerCase()).valueOf()
                : undefined
            );
          }
        });
        nameList.length > 1 && delete newValues[name];
      } else if (/^Range/i.test(type)) {
        const mode =
          typeOf(formItem.props?.mode) === "undefined"
            ? "date"
            : typeOf(formItem.props?.mode) === "array"
            ? formItem.props.mode[0]
            : formItem.props?.mode
            ? formItem.props.mode
            : "date";
        if (/\,/.test(name)) {
          name.split(",").forEach((item, index) => {
            if (/^(week|month|year)/.test(mode)) {
              if (index === 0) {
                setValue(
                  newValues,
                  item,
                  value[index]
                    ? moment(value[index]).startOf(mode).valueOf()
                    : undefined
                );
              } else {
                setValue(
                  newValues,
                  item,
                  value[index]
                    ? moment(value[index]).endOf(mode).valueOf()
                    : undefined
                );
              }
            } else {
              setValue(newValues, item, value[index]?.valueOf() || undefined);
            }
          });
          delete newValues[name];
        } else {
          setValue(
            newValues,
            name,
            value.map((item, index) => {
              if (/^(week|month|year)/.test(mode)) {
                if (index === 0) {
                  return moment(value).startOf(mode).valueOf() || undefined;
                } else {
                  return moment(value).endOf(mode).valueOf() || undefined;
                }
              } else {
                return item.valueOf();
              }
            })
          );
        }
      } else if (/Upload/i.test(formItem.type)) {
        const { FILE_SERVER } = getConstants();
        if (Array.isArray(value)) {
          const pics = value.map(item => {
            return item.response || item;
          });
          const {
            minCount,
            maxCount,
            filedName = "mediaUrl",
            returnSize
          } = formItem;
          if (minCount > 1 || maxCount > 1) {
            if (filedName) {
              setValue(
                newValues,
                name,
                pics.map(item => {
                  let obj = {};
                  obj.width = item.width;
                  obj.height = item.height;
                  obj[filedName] =
                    item.id ||
                    item.mediaUrl ||
                    item?.url.replace(FILE_SERVER, "");
                  return obj;
                })
              );
            } else {
              var newPics = pics.map(
                item =>
                  item.mediaUrl || item.id || item?.url.replace(FILE_SERVER, "")
              );
              setValue(newValues, name, newPics);
            }
          } else {
            // todo 需要处理嵌套
            if (returnSize) {
              var pic = pics[0];
              newValues.width = pic.width;
              newValues.height = pic.height;
            }
            setValue(
              newValues,
              name,
              pics[0]?.id || pics[0]?.url?.replace(FILE_SERVER, "") || null
            );
          }
        }
      } else if (/Video/i.test(type)) {
        // todo 处理嵌套 原来的name 可能删除
        if (Array.isArray(value)) {
          const videos = value.map(item => {
            return item.response || item;
          });
          const {
            filedNames = {
              cover: "videoCoverPic",
              duration: "videoCoverDuration",
              url: "videoCoverUrl"
            }
          } = formItem;
          videos.forEach(item => {
            newValues[filedNames.cover] = item.cover;
            newValues[filedNames.duration] = item.width
              ? item.duration * 1000
              : item.duration;
            newValues[filedNames.url] = item.viewUrl;
          });
        }
      } else if (/NumberRange/i.test(type)) {
        if (/\,/.test(name)) {
          name.split(",").forEach((item, index) => {
            setValue(newValues, item, value[index]);
          });
          delete newValues[name];
        }
      } else if (/Editor/i.test(type)) {
        if (typeOf(value) === "object") {
          setValue(
            newValues,
            name,
            value.toHTML() === "<p></p>" ? "" : value.toHTML()
          );
        }
      } else if (
        /inputNumber/i.test(type) &&
        /money|price/.test(formItem.mode)
      ) {
        setValue(newValues, name, value * 100);
      } else if (/(input|textarea)$/i.test(type)) {
        if (typeof value === "string") {
          setValue(newValues, name, value.trim());
          if (encode === true) {
            setValue(newValues, name, getEncodeUrl(value));
          }
          if (formItem.mode === "mpH5") {
            var prefix = "mp://pages/webView?url=";
            if (!value.includes(prefix)) {
              setValue(newValues, name, getEncodeUrl(prefix + value, "?url="));
            } else {
              setValue(newValues, name, getEncodeUrl(value, "?url="));
            }
          }
        }
      }
    });
  return newValues;
}
/**
 * 获取一些常量 比如 FILE_SERVER
 *
 * @returns {object}
 */
export function getConstants() {
  const MAIN_HOST = "idongjia.cn";
  const ENV_TAG = window.location.host.includes(MAIN_HOST)
    ? window.location.host.split(".")[0].split("-")[1] || ""
    : process.env.DEV_TYPE;
  return {
    ENV_TAG,
    FILE_SERVER: `${window.location.protocol}//file${
      ENV_TAG ? "-" + ENV_TAG : ""
    }.idongjia.cn/`,
    ROOT_URL: `${window.location.protocol}//admin${
      ENV_TAG ? "-" + ENV_TAG : ""
    }.${MAIN_HOST}/`,
    H5_HOST: `${window.location.protocol}//m.idongjia.cn/${
      ENV_TAG ? ENV_TAG + "/" : ""
    }`
  };
}
// 获取嵌套对象的值 最高支持两层嵌套
export function getValue(obj, name) {
  if (/\./g.test(name)) {
    var arr = name.split(".");
    if (arr.length === 2) {
      if (obj[arr[0]]) {
        return obj[arr[0]][arr[1]];
      }
    }
  } else {
    return obj[name];
  }
}
// 设置嵌套对象的值 最高支持两层嵌套
export function setValue(obj, name, value) {
  if (/\./g.test(name)) {
    var arr = name.split(".");
    if (arr.length === 2) {
      if (obj[arr[0]]) {
        obj[arr[0]][arr[1]] = value;
      }
    }
  } else {
    obj[name] = value;
  }
}
/**
 * detail详情数据 转成form表单需要的values 用于form.setFieldValues
 *
 * @param {object} detail
 * @param {object[]} formItems
 * @param {object[]} names 可不传 如果是多张图片 后台返回的数组结构中的对象不是madiaUrl,比如是 imageUrl 则需要指明 相应的key 如：names: [{type: 'upload',name: imageList,key: 'imageUrl'}]
 * @returns {object} values 传给setFieldsValue函数
 */
export function transformDetail({ detail, formItems }) {
  const { FILE_SERVER } = getConstants();
  const values = {};
  formItems.forEach((item, index) => {
    const { name, type, initialValue, mode, encode } = item;
    const value = getValue(detail, name);
    if (mode === "mpJump" && value) {
      let mpJumpItem = getMpJumpItem({ formItems, index, detail });
      if (mpJumpItem) {
        let newVal = decodeURIComponent(value).replace(mpJumpItem.prefix, "");
        values[name] = newVal;
        return;
      }
    }
    if (/Date|Week|Month/i.test(type)) {
      values[name] = value
        ? moment(value)
        : initialValue
        ? initialValue
        : undefined;
    } else if (/^Range/i.test(type)) {
      const nameArr = name.split(",");
      const arr = [];
      arr[0] = detail[nameArr[0]] ? moment(detail[nameArr[0]]) : undefined;
      arr[1] = detail[nameArr[1]] ? moment(detail[nameArr[1]]) : undefined;
      values[name] = detail[nameArr[0]]
        ? arr
        : initialValue
        ? initialValue
        : [undefined, undefined];
    } else if (/^NumberRange/i.test(type)) {
      const nameArr = name.split(",");
      const arr = [];
      arr[0] = detail[nameArr[0]] ?? undefined;
      arr[1] = detail[nameArr[1]] ?? undefined;
      values[name] = values[name] = initialValue ? initialValue : arr;
    } else if (/Upload/i.test(type)) {
      if (typeOf(value) === "array") {
        let arr = [];
        let key = "mediaUrl";
        value.forEach((item, index) => {
          var url = _.isObject(item) ? item[key] : item;
          let obj = {};
          obj.url = FILE_SERVER + url;
          obj.uid = url;
          arr.push(obj);
        });
        values[name] = arr;
      } else if (value) {
        values[name] = [{ url: FILE_SERVER + value, uid: value }];
      }
    } else if (/Video/i.test(type)) {
      if (value) {
        const {
          filedNames = {
            cover: "videoCoverPic",
            duration: "videoCoverDuration",
            url: "videoCoverUrl"
          }
        } = item;
        var videoObj = {
          status: "done",
          uid: -1,
          response: {
            url: detail[filedNames.url],
            viewUrl: detail[filedNames.url],
            cover: detail[filedNames.cover],
            duration: +detail[filedNames.duration]
          },
          thumbUrl: FILE_SERVER + detail[filedNames.cover]
        };
        values[name] = [videoObj];
      } else {
        values[name] = undefined;
      }
    } else if (/Editor/i.test(type)) {
      values[name] = BraftEditor.createEditorState(value);
    } else if (/inputNumber/i.test(type) && /money|price/.test(mode)) {
      values[name] = value === 0 ? 0 : value ? value / 100 : undefined;
    } else if (/input|textarea/i.test(type)) {
      if (encode && value) {
        values[name] = decodeURIComponent(value);
      } else if (mode === "mpH5") {
        const prefix = "mp://pages/webView?url=";
        let newValue = decodeURIComponent(value);
        newValue = newValue.replace(prefix, "");
        values[name] = newValue;
      } else {
        values[name] = value;
      }
    } else if (name) {
      values[name] = value ?? initialValue ?? undefined;
    }
  });
  return values;
}
/**
 * 获取表格项数值根据类型转化
 * @param {*} value - 值
 * @param {string} type - 表格类型 有 date preview等
 * @param {object} column - columns列表中的的item
 * @returns {*} value
 */
function getFieldValueByType({ value, type, column }) {
  switch (type) {
    case "date":
      return moment(value).format("YYYY-MM-DD");
    case "dateMinute":
      return moment(value).format("YYYY-MM-DD HH:mm");
    case "datetime":
      return moment(value).format("YYYY-MM-DD HH:mm:ss");
    case "status":
      return column.enum[value];
    case "preview":
    case "pic":
      return appState.state.FILE_SERVER + value;
    default:
      return value;
  }
}
/**
 * 导出excel方法
 * @param {any[]} dataSource - 表格数据
 * @param {any[]} columns - 表格列
 * @param {string} sheetName=Sheet1 - 工作表名称
 * @param {string} fileName=Date.now - 下载的文件名，不需要传入后缀名默认.xlsx
 */
export function exportExcel({
  dataSource,
  columns,
  sheetName = "Sheet1",
  fileName = Date.now()
}) {
  var fieldNames = _.chain(columns)
    .reject(item => item.title === "操作")
    .keyBy("dataIndex")
    .value();
  var arr = [];
  _.forEach(dataSource, item => {
    var obj = {};
    _.forEach(item, (value, key) => {
      if (key in fieldNames) {
        var name = fieldNames[key].title;
        obj[name] = getFieldValueByType({
          value,
          type: fieldNames[key].type,
          column: fieldNames[key]
        });
      }
    });
    arr.push(obj);
  });
  const jsonWorkSheet = xlsx.utils.json_to_sheet(arr);
  const workBook = {
    SheetNames: [sheetName],
    Sheets: {
      [sheetName]: jsonWorkSheet
    }
  };
  xlsx.writeFile(workBook, fileName + ".xlsx");
}
/**
 * 获取布尔值 用作show
 * @param {*} bool - 需要判断的值
 * @param {array} payload - 传参数组
 * @returns {boolean}
 */
export function getBoolean(bool, ...payload) {
  if (typeof bool === "boolean") {
    return bool;
  } else if (typeof bool === "function") {
    return bool(...payload);
  } else if (bool === undefined) {
    return true;
  } else {
    return !!bool;
  }
}
/**
 * 获取encode后的url
 * @param {string} url - 网址路径
 * @returns {string}
 */
export function getEncodeUrl(url, seq = "?") {
  const index = url.indexOf(seq);
  if (index === -1) return url;
  const urlArr = url.split(seq);
  const urlBefore = urlArr[0];
  const urlAfter = urlArr[1];
  return urlBefore + seq + encodeURIComponent(urlAfter);
}
/**
 * 获取小程序跳转item
 * @param {array} formItems - 表单数组
 * @returns {object} detail - 详情对象
 */
export function getMpJumpItem({ formItems, index, detail }) {
  let appletAddrTypeName = formItems[index - 1].name;
  let appletAddrTypeValue = getValue(detail, appletAddrTypeName);
  return mpJumpObj[appletAddrTypeValue];
}
/**
 * 获取小程序跳转item
 * @param {array} formItems - 表单数组
 * @returns {object} detail - 详情对象
 */
export function getMpJumpItemByAppletAddrType(appletAddrType) {
  return mpJumpObj[appletAddrType];
}
/**
 * 设置小程序跳转参数formItem的相关属性
 * @param {number} appletAddrType - 小程序跳转类型
 * @param {object} formItem - 小程序跳转参数formItem对象
 * @param {object} mpJumpItem - 小程序跳转协议item
 */
export function setMpUrlFormItem({ appletAddrType, formItem, mpJumpItem }) {
  if (appletAddrType) {
    mpJumpItem = mpJumpObj[appletAddrType];
  }
  const { type, query, desc } = mpJumpItem;
  formItem.type = type;
  if (query === false) {
    formItem.disabled = true;
    formItem.required = false;
    formItem.placeholder = desc;
  } else {
    formItem.disabled = false;
    formItem.required = true;
    formItem.placeholder = "请输入" + desc;
  }
}
/**
 * 返回小程序跳转参数formItem的相关属性
 * @param {number} appletAddrType - 小程序跳转类型
 * @param {object} attrObj - 小程序跳转协议formItem属性对象
 */
export function getMpJumpFormItemAttrObj(appletAddrType) {
  const mpJumpItem = getMpJumpItemByAppletAddrType(appletAddrType);
  const attrObj = {};
  if (mpJumpItem) {
    const { type, query, desc } = mpJumpItem;
    attrObj.type = ["select", "select", type];
    if (query === false) {
      attrObj.disabled = [false, false, true];
      attrObj.required = [false, true, false];
      attrObj.placeholder = ["请输入", "请选择", "无需参数"];
    } else {
      attrObj.disabled = [false, false, false];
      attrObj.required = [false, true, true];
      attrObj.placeholder = ["请输入", "请选择", "请输入" + desc];
    }
  }
  return attrObj;
}
/**
 * options数组转化为obj
 * @param {any[]} options
 * @returns {object}
 */
export function optionsToObj(options) {
  const obj = {};
  options.forEach(item => {
    obj[item.value] = item.label;
  });
  return obj;
}
// 图片元素转base64
function getBase64Image(img) {
  let canvas = document.createElement("canvas");
  canvas.width = img.naturalWidth;
  canvas.height = img.naturalHeight;
  let ctx = canvas.getContext("2d");
  ctx.fillStyle = "#fff";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight);
  let dataURL = canvas.toDataURL("image/png");
  return dataURL;
}
// base64图片转为blob
function getBlobImage(dataurl) {
  let arr = dataurl.split(",");
  let mime = arr[0].match(/:(.*?);/)[1];
  let bstr = atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}
// 复制图片
export function copyImage(dom, successCB, failCB) {
  let dataurl = getBase64Image(dom);
  let blob = getBlobImage(dataurl);
  navigator.clipboard
    .write([
      new window.ClipboardItem({
        [blob.type]: blob
      })
    ])
    .then(
      function () {
        successCB && successCB();
      },
      function () {
        failCB && failCB();
      }
    );
}
// icon转简写
export function getIconType(type) {
  switch (type) {
    case "up":
      return "arrow-up";
    case "down":
      return "arrow-down";
    case "video":
      return "video-camera";
    case "list":
      return "unordered-list";
    case "clock":
      return "clock-circle";
    case "money":
    case "coupon":
      return "money-collect";
    default:
      return type;
  }
}
// icon转简写
export function getIconTitle(type) {
  switch (type) {
    case "edit":
      return "编辑";
    case "delete":
      return "删除";
    case "eye":
      return "查看";
    case "up":
      return "上线";
    case "down":
      return "下线";
    case "audit":
      return "审核";
    default:
      return "";
  }
}
/**
 * 处理js小数处理的精度问题
 * @param {number|string} num - 数字
 * @param {string} type - 运算类型 乘法或者除法 * | /
 * @param {number} multiple - 乘法或者除法的倍数
 */
export function getFloatNum(num, type = "*", multiple = 100) {
  if (!num) return num;
  let numStr = num + "";
  let dotIndex = numStr.indexOf(".");
  if (dotIndex === -1) {
    if (type === "*") {
      return num * multiple;
    } else {
      return num / multiple;
    }
  }
  let afterDotCount = numStr.length - dotIndex - 1;
  let multipleNum = Math.pow(10, afterDotCount);
  var int = (num * multipleNum).toFixed(0);
  return type === "*"
    ? (int * multiple) / multipleNum
    : int / (multipleNum * multiple);
}
// 判断数字range是否重叠
export function isRangeOverlap(list) {
  var sortRangeList = _.chain(list)
    .sortBy(item => item[0])
    .flattenDeep()
    .value();
  var sortList = _.chain(list)
    .flattenDeep()
    .sortBy(item => item)
    .value();
  return !_.isEqual(sortRangeList, sortList);
}
/**
 * 获取表单订的 validNameList
 */
export function getValidNameList(formItems = []) {
  return _.chain(formItems)
    .filter(item => {
      return item.exclude !== true;
    })
    .map("name")
    .value();
}
export const downloadFile = (blob, fileName) => {
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, fileName);
  } else {
    var link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    window.URL.revokeObjectURL(link.href);
    link = null;
  }
};
